package cn.stylefeng.guns.modular.hp.utils;

import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;

public class HttpUtils {

    public static String getBrowser(HttpServletRequest request) {
        String userAgent = request.getHeader("USER-AGENT").toLowerCase();
        if (userAgent != null) {
            if (userAgent.indexOf("msie") >= 0) {
                return "IE";
            } else if (userAgent.indexOf("mozilla") >= 0) {
                return "FF";
            } else if (userAgent.indexOf("applewebkit") >= 0) {
                return "CH";
            } else if (userAgent.indexOf("safari") >= 0) {
                return "SF";
            } else if (userAgent.indexOf("opera") >= 0) {
                return "OP";
            }
        }
        return null;
    }

    public static String getContentDisposition(HttpServletRequest request, String filename) {
        String browser = getBrowser(request);
        String contentDisposition = "";
        try {
            if ("IE".equals(browser)) {
                contentDisposition = "attachment; filename=" + URLEncoder.encode(filename, "UTF-8").replace("+", "%20");
            } else if ("CH".equals(browser)) {
                contentDisposition = "attachment; filename=" + MimeUtility.encodeText(filename, "UTF8", "B");
            } else if ("SF".equals(browser)) {
                contentDisposition = "attachment; filename=" + new String(filename.getBytes("UTF-8"), "ISO8859-1");
            } else {
                contentDisposition = "attachment; filename*=UTF-8''" + URLEncoder.encode(filename, "UTF-8").replace("+", "%20");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return contentDisposition;
    }
}
